package cn.zl.rtsp.udp;

import cn.hutool.core.util.HexUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

public class UDPSocket implements Runnable {

    protected static final Logger logger = LoggerFactory.getLogger(UDPSocket.class);

    public final int MAX_UDP_PACK_SIZE = 8192;

    protected DatagramSocket socket;
    // protected ProtocolHandler m_ProtocolHandler;
    protected Thread thread;
    protected volatile boolean runnable;

    public boolean open(int nLocalPort) {
        InetSocketAddress sa = new InetSocketAddress(nLocalPort);
        return open(sa);
    }

    public boolean open(SocketAddress sa) {
        close();
        runnable = true;
        try {
            //open socket
            socket = new DatagramSocket(sa);
            socket.setReceiveBufferSize(65535);
            //create thread
            thread = new Thread(this, "UDPSocketThread");
            thread.start();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }
        return true;
    }

    public void close() {
        runnable = false;
        if (socket != null) {
            socket.close();
        }
        if (thread != null) {
            try {
                thread.join(2000);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    @Override
    public void run() {
        byte[] byBuffer = new byte[MAX_UDP_PACK_SIZE];
        DatagramPacket dp = new DatagramPacket(byBuffer, byBuffer.length);
        while (runnable) {
            try {
                socket.receive(dp);
                byte[] data = dp.getData();
                int length = dp.getLength();
                String hex = HexUtil.encodeHexStr(data, false);
                logger.info("length: {}  hex: {}", length, hex);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }


}
